package com.test.ecdsa;

import com.google.common.base.Strings;
import com.test.utils.Base64Utils;
import com.test.utils.RSAUtils;
import org.apache.shiro.codec.Base64;

import javax.crypto.Cipher;
import java.nio.charset.StandardCharsets;
import java.security.*;
import java.security.interfaces.ECPrivateKey;
import java.security.interfaces.ECPublicKey;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.ECGenParameterSpec;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Arrays;

public class ECDSADemo {

    private static final String SIGNALGORITHMS = "SHA256withECDSA";

    private static final String ALGORITHM = "EC";

    private static final String SECP256K1 = "secp256k1";

    private static final String PRIVATE_KEY = "MD4CAQAwEAYHKoZIzj0CAQYFK4EEAAoEJzAlAgEBBCBj+9rlzGYr+74IFJcSKVf1dthjJzpHuaiPvtQV9PKORQ==";

    private static final String PUBLIC_KEY = "MFYwEAYHKoZIzj0CAQYFK4EEAAoDQgAEab684c8YeNg7Du759bXoeB/79KRyKK4zpkZxwrjrzmKLjKwvMkFmThFly9Pljz+mp2baue+/EhhzRs9vt8ZLkg==";

    public static void main(String[] args) throws Exception {
        demo1();
//        genKeys();
//        demo1(str);
//        genKeys(1142);
    }

//    public static void demo1(String str) {
//        try {
//            KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("EC");
//            keyPairGenerator.initialize(256);
//
//            KeyPair keyPair = keyPairGenerator.generateKeyPair();
//            ECPublicKey ecPublicKey = (ECPublicKey) keyPair.getPublic();
//            ECPrivateKey ecPrivateKey = (ECPrivateKey) keyPair.getPrivate();
//            // 2.执行签名
//            PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(ecPrivateKey.getEncoded());
//            KeyFactory keyFactory = KeyFactory.getInstance("EC");
//
//            PrivateKey privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);
//            Signature signature = Signature.getInstance("SHA512withECDSA");
//            signature.initSign(privateKey);
//
//            signature.update(str.getBytes());
//            byte[] sign = signature.sign();
//
//            // 验证签名
//            X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(ecPublicKey.getEncoded());
//            keyFactory = KeyFactory.getInstance("EC");
//            PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec);
//            signature = Signature.getInstance("SHA1withECDSA");
//            signature.initVerify(publicKey);
//            signature.update(str.getBytes());
//
//            boolean bool = signature.verify(sign);
//            System.out.println(bool);
//
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }

    public static void genKeys() throws Exception {
        // 生成公钥私钥
        ECGenParameterSpec ecSpec = new ECGenParameterSpec(SECP256K1);
        KeyPairGenerator kf = KeyPairGenerator.getInstance(ALGORITHM);
        kf.initialize(ecSpec, new SecureRandom());
        KeyPair keyPair = kf.generateKeyPair();
        PublicKey publicKey = keyPair.getPublic();
        PrivateKey privateKey = keyPair.getPrivate();
        //密钥转16进制字符串
        System.out.println(Strings.lenientFormat("private static final String PRIVATE_KEY=\"%s\";", Base64.encodeToString(privateKey.getEncoded())));
        System.out.println(Strings.lenientFormat("private static final String PUBLIC_KEY=\"%s\";", Base64.encodeToString(publicKey.getEncoded())));
    }

    public static void demo1() throws Exception {
        String str = "哈喽";
        byte[] bytes = encryptPublicKey(publicKey(PUBLIC_KEY), str.getBytes(StandardCharsets.UTF_8));
        System.out.println(bytes.length);
        System.out.println(Arrays.toString(bytes));
        bytes = encryptPrivateKey(privateKey(PRIVATE_KEY), bytes);
        System.out.println(new String(bytes, StandardCharsets.UTF_8));
    }

    /**
     * 公钥加密
     */
    public static byte[] encryptPublicKey(Key publicKey, byte[] plainTextData) throws Exception {
        try {
            Cipher cipher = Cipher.getInstance("EC");
            cipher.init(Cipher.ENCRYPT_MODE, publicKey);
            byte[] output = cipher.doFinal(plainTextData);
            return output;
        } catch (NoSuchAlgorithmException e) {
            throw new Exception("无此加密算法");
        }
    }

    /**
     * 私钥解密
     */
    public static byte[] decryptPrivateKey(Key privateKey, byte[] cipherData) throws Exception {
        try {
            Cipher cipher = Cipher.getInstance("EC");
            cipher.init(Cipher.DECRYPT_MODE, privateKey);
            byte[] output = cipher.doFinal(cipherData);
            return output;
        } catch (NoSuchAlgorithmException e) {
            throw new Exception("无此解密算法");
        }
    }


    /**
     * 私钥加密过程
     */
    public static byte[] encryptPrivateKey(Key privateKey, byte[] plainTextData) throws Exception {
        try {
            Cipher cipher = Cipher.getInstance("EC");
            cipher.init(Cipher.ENCRYPT_MODE, privateKey);
            byte[] output = cipher.doFinal(plainTextData);
            return output;
        } catch (NoSuchAlgorithmException e) {
            throw new Exception("无此加密算法");
        }
    }

    /**
     * 公钥解密过程
     */
    public static byte[] decryptPublic(Key publicKey, byte[] cipherData) throws Exception {
        try {
            // 使用默认RSA
            Cipher cipher = Cipher.getInstance("EC");
            cipher.init(Cipher.DECRYPT_MODE, publicKey);
            byte[] output = cipher.doFinal(cipherData);
            return output;
        } catch (NoSuchAlgorithmException e) {
            throw new Exception("无此解密算法");
        }
    }

    /**
     * 私钥签名
     */
    public static byte[] signature(ECPrivateKey privateKey, byte[] plainTextData)
            throws Exception {
        try {
            Signature signature = Signature.getInstance("SHA1withECDSA");
            signature.initSign(privateKey);
            signature.update(plainTextData);
            byte[] sign = signature.sign();
            return sign;
        } catch (NoSuchAlgorithmException e) {
            throw new Exception("无此加密算法");
        }
    }

    /**
     * 公钥验签
     */
    public static boolean checkSignature(ECPublicKey publicKey, byte[] cipherData, byte[] sign)
            throws Exception {
        boolean result = false;
        try {
            Signature signature = Signature.getInstance("SHA1withECDSA");
            signature.initVerify(publicKey);
            signature.update(cipherData);
            result = signature.verify(sign);
            return result;
        } catch (NoSuchAlgorithmException e) {
            throw new Exception("无此解密算法");
        }
    }

    public static Key publicKey(String base64Key) throws Exception {
        byte[] keyBytes = Base64Utils.decode2Bytes(base64Key);
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM);
        Key publicK = keyFactory.generatePublic(keySpec);
        return publicK;
    }

    public static Key privateKey(String base64Key) throws Exception {
        byte[] keyBytes = Base64Utils.decode2Bytes(base64Key);
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM);
        Key privateK = keyFactory.generatePrivate(keySpec);
        return privateK;
    }
}
